#include "Msg.h"

//Json的序列化 
bool CMsg::Serialize(const Json::Value& value, std::string& body)
{
    //Json里的格式化写入类
    Json::StreamWriterBuilder swb;
    //使用智能指针管理new出来的对象
    std::unique_ptr<Json::StreamWriter> sw(swb.newStreamWriter());

    std::stringstream ss;
    //将Json格式化成为ss
    int ret = sw->write(value, &ss);
    if (ret != 0) {
        return false;
    }
    body = ss.str();
    return true;
}

//Json的反序列化
bool CMsg::UnSerialize(const std::string& body, Json::Value& value)
{
    //Json中的将string格式化读入类
    Json::CharReaderBuilder crb;
    std::unique_ptr<Json::CharReader> cr(crb.newCharReader());

    std::string err;
    //反序列化
    bool ret = cr->parse(body.c_str(), body.c_str() + body.size(), &value, &err);
    if (ret == false) {                                                                                                                                                                  
        return false;
    }
    return true;
}

CMsg::CMsg()
{
    user_id_ = -1;
    socket_fd_ = -1;
    msg_type_ = -1;
    response_ = -1;
    msg_.clear();
}

CMsg::CMsg(enum MSG_TYPE msg_type)
{
    msg_type_ = msg_type;
    socket_fd_ = -1;
    response_ = -1;
    msg_.clear();
}

CMsg::~CMsg()
{}

//解析成为CMsg，服务端填充客户端的fd，客户端填充服务端的fd
bool CMsg::ParseString(int socket_fd, std::string& body)
{
    socket_fd_ = socket_fd;

    Json::Value tmp;
    if(UnSerialize(body, tmp) == false)
        return false;
    
    user_id_ = tmp["user_id"].asInt();
    msg_type_ = tmp["msg_type"].asInt();
    response_ = tmp["response"].asInt();
    msg_ = tmp["msg"];

    return true;
}

//将CMsg序列化成为string
bool CMsg::GetString(std::string& body)
{
    Json::Value tmp;

    tmp["user_id"] = user_id_;
    tmp["socket_fd"] = socket_fd_;
    tmp["msg_type"] = msg_type_;
    tmp["response"] = response_;
    tmp["msg"] = msg_;

    if(Serialize(tmp, body) == false)
        return false;
    
    return true;
}

void CMsg::SetNameValue(const std::string& name, const std::string val)
{
    msg_[name] = val;
}

void CMsg::SetNameValue(const std::string& name, int val)
{
    msg_[name] = val;
}

std::string CMsg::GetValue(const std::string& name)
{
    if(!msg_.isMember(name)){
        return "";
    }

    return msg_[name].asString();
}

void CMsg::Clear()
{
    user_id_ = -1;
    msg_type_ = -1;
    response_ = -1;
    msg_.clear();
}






